#include "netlib.h"
#include "riolib.h"

void echo(int connfd);

int main(int argc, char** argv)
{
	int listenfd, connfd, port, clientlen;
	struct sockaddr_in clientaddr;
	struct hostent *hp;
	char *haddrp;
	if(argc != 2)
	{
		fprintf(stderr, "usage: %s <port>\n", argv[0]);
		return 0;
	}
	port = atoi(argv[1]);
	listenfd = open_listenfd(port);
	printf("listenfd: %d\n", listenfd);
	while(1)
	{
		clientlen = sizeof(clientaddr);
		connfd = accept(listenfd, (SA*)&clientaddr, &clientlen);

		hp = gethostbyaddr((const char*)&clientaddr.sin_addr.s_addr, 
				sizeof(clientaddr.sin_addr.s_addr), AF_INET);
		haddrp = inet_ntoa(clientaddr.sin_addr);
		printf("server connected to %s (%s)\n", hp->h_name, haddrp);
		echo(connfd);
		close(connfd);
	}
	return 0;
}

void echo(int connfd)
{
	size_t n;
	char buf[MAXLINE];
	rio_t rio;

	rio_init(&rio, connfd);
	while((n = rio_readline(&rio, buf, MAXLINE)) != 0) 
	{
		sprintf(buf, "%d\0", n);
		printf("server received %d bytes\n", n);
		rio_writen(connfd, buf, strlen(buf));
	}
}
